package com.dllo.lanou.cookapp.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.dllo.lanou.cookapp.R;
import com.dllo.lanou.cookapp.adapter.AddCookStrpAdapter;
import com.dllo.lanou.cookapp.adapter.CommentAdapter;
import com.dllo.lanou.cookapp.adapter.CommentReplyAdapter;

import com.dllo.lanou.cookapp.adapter.CookStepAdapter;
import com.dllo.lanou.cookapp.entity.AddCookEntity;
import com.dllo.lanou.cookapp.entity.AddCookStepEntity;
import com.dllo.lanou.cookapp.entity.Collection;
import com.dllo.lanou.cookapp.entity.Comment;
import com.dllo.lanou.cookapp.entity.Reply;
import com.dllo.lanou.cookapp.entity.User;
import com.dllo.lanou.cookapp.utils.ScrollViewUtil;
import com.dllo.lanou.cookapp.view.MyListView;
import com.dllo.lanou.cookapp.volly.GetVolleyImage;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class ShowCookingDesActivity extends AppCompatActivity implements View.OnClickListener {
   private  AddCookStepEntity addCookStepEntity = null;
    @Bind(R.id.show_des_back)
    ImageView show_des_back;

    @Bind(R.id.show_des_collet)
    ImageView show_des_collet;
    @Bind(R.id.show_des_guanzhu)
    ImageView show_des_guanzhu;
    @Bind(R.id.show_des_userimg)
    ImageView show_des_userimg;
    @Bind(R.id.show_des_img)
    ImageView show_des_img;


    @Bind(R.id.show_des_name)
    TextView show_des_name;
    @Bind(R.id.show_des_guanzhu_count)
    TextView show_des_guanzhu_count;
    @Bind(R.id.show_des_username)
    TextView show_des_username;
    @Bind(R.id.show_des_tips)
    TextView show_des_tips;
    @Bind(R.id.show_des_card)
    TextView show_des_card;
    @Bind(R.id.show_des_food)
    TextView show_des_food;

    @Bind(R.id.show_des_steplistview)
    MyListView listView;
    @Bind(R.id.show_des_comment)
     TextView  show_des_comment;

    @Bind(R.id.commentlistview)
    MyListView commentlistview;

    @Bind(R.id.scrollView)
    ScrollView scrollView;
    private CookStepAdapter adapter;
    private Button btn_comment, btn_reply;
    private EditText edt_reply;

    private CommentAdapter commentAdapter;
    private CommentReplyAdapter commentReplyAdapter;

    private static final int ONE_COMMENT_CODE = -1;
    ScrollViewUtil  scrollViewUtil= new ScrollViewUtil();
    private List<Comment> commentList = new ArrayList<>();
    private List<Reply> replyList = new ArrayList<>();
    private List<Comment> comments = new ArrayList<>();
    List<Reply>  replyLists = new ArrayList<Reply>();
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if(msg.what == 1){

                comments = (List<Comment>) msg.obj;
                Collections.reverse(comments);
                commentAdapter.clearList();
                commentAdapter.updateList(comments);
                commentAdapter.notifyDataSetChanged();
            }
        }
    };
private User user;
    private int count = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_cooking_des);
        ButterKnife.bind(this);
        user = BmobUser.getCurrentUser(this,User.class);
        if (user!=null){
            show_des_collet.setOnClickListener(this);
            //收藏
            initCollection();
        }
        else
        {  // count=0;
            Toast.makeText(ShowCookingDesActivity.this,"请先去登录！",Toast.LENGTH_LONG).show();
        }

        scrollView.smoothScrollTo(0, 0);
        addCookStepEntity = new AddCookStepEntity();
        adapter = new CookStepAdapter(this);
        listView.setAdapter(adapter);
        ScrollViewUtil.setListViewHeightBasedOnChildren(listView);
        show_des_comment.setOnClickListener(this);
        commentReplyAdapter = null;
        commentAdapter = new CommentAdapter(this, commentList,
                replyToCommentListener, commentReplyAdapter,
                replyToReplyListener);
        commentlistview.setAdapter(commentAdapter);
        ScrollViewUtil.setListViewHeightBasedOnChildren(commentlistview);
        commentlistview.setFocusable(false);
        Intent intent = this.getIntent();
        addCookStepEntity=(AddCookStepEntity)intent.getSerializableExtra("entity");
        if (addCookStepEntity != null){
            show_des_name.setText(addCookStepEntity.getName());
            show_des_tips.setText(addCookStepEntity.getTips());
            show_des_card.setText(addCookStepEntity.getLabel());
            show_des_food.setText(addCookStepEntity.getFood());
            if (addCookStepEntity.getBmob_img() != null){
                GetVolleyImage.getNetWorkImg(addCookStepEntity.getBmob_img(), show_des_img);
            }
            User user = addCookStepEntity.getAuthor();
            show_des_username.setText(user.getUsername());
            if (user.getImg() != null) {
                Log.i("图片", user.getImg() + "");
                user.getImg().loadImage(this,show_des_userimg);
            }
            List<AddCookEntity> entity = addCookStepEntity.getAddCookEntities();
            Log.i("AddCookEntity",entity.size()+"");
            adapter.addData(entity);
        }
//评论
        initComment();


        }

    private void initCollection() {
//当

            BmobQuery<Collection>  query = new BmobQuery<>();
            query.addWhereEqualTo("user",user);
            query.addWhereEqualTo("addCookStepEntity",addCookStepEntity);
            query.findObjects(this, new FindListener<Collection>() {
                @Override
                public void onSuccess(List<Collection> list) {
                    Log.i("神+",list.size()+"");
                    if (list.size()==1){
                        count=1;
                        show_des_collet.setImageResource(R.drawable.bottom_collect_yellow);
                        collection= list.get(0);
                    }

                }

                @Override
                public void onError(int i, String s) {

                }
            });
        }




    private void  initComment(){
       //查询某张表的所有评论
       BmobQuery<Comment> query = new BmobQuery<Comment>();

       query.addWhereEqualTo("post",new BmobPointer(addCookStepEntity));
       query.include("user,post.author");
       query.findObjects(this, new FindListener<Comment>() {
           @Override
           public void onSuccess(List<Comment> list) {

               Message msg  = new Message();
               msg.what=1;
               msg.obj = list;
               handler.sendMessage(msg);



           }

           @Override
           public void onError(int i, String s) {

           }
       });


   }



    /**
     * 弹出评论的对话框
     *
     * @param parentPositon
     *            父节点的position
     * @param childPostion
     *            子节点的position
     * @return
     */
    protected Dialog onCreateDialog(final int parentPositon, final int childPostion) {
        final Dialog customDialog = new Dialog(this);
        LayoutInflater inflater = getLayoutInflater();
        View mView = inflater.inflate(R.layout.dialog_comment, null);
        edt_reply = (EditText) mView.findViewById(R.id.edt_comments);
        btn_reply = (Button) mView.findViewById(R.id.btn_send);

        customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        customDialog.setContentView(mView);
        customDialog.show();

        btn_reply.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (childPostion) {
                    case ONE_COMMENT_CODE:
                        if (TextUtils.isEmpty(edt_reply.getText().toString())) {
                            Toast.makeText(ShowCookingDesActivity.this, "内容不能为空",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Comment comment = new Comment();
                            User user = BmobUser.getCurrentUser(ShowCookingDesActivity.this,User.class);
                            comment.setUser(user);
                            comment.setPost(addCookStepEntity);
                            String content =edt_reply.getText().toString();
                            comment.setContent(content);
                            comment.save(ShowCookingDesActivity.this, new SaveListener() {

                                @Override
                                public void onSuccess() {
                                    // TODO Auto-generated method stub
                                    Log.i("life", "评论发表成功");
                                    initComment();
                                }

                                @Override
                                public void onFailure(int code, String msg) {
                                    // TODO Auto-generated method stub
                                    Log.i("life", "评论失败");
                                }
                            });

                            customDialog.dismiss();
                            edt_reply.setText("");
                        }
                        break;
                    default:
                        if (TextUtils.isEmpty(edt_reply.getText().toString())) {
                            Toast.makeText(ShowCookingDesActivity.this, "内容不能为空",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Reply reply = new Reply();
                            User user = BmobUser.getCurrentUser(ShowCookingDesActivity.this,User.class);

                            reply.setUsername(user.getUsername());
                            reply.setContent(edt_reply.getText().toString());

                            if (parentPositon != -1) {
                                Log.i("bmob","更新成功：++"+comments.get(parentPositon).getReplies().get(childPostion)
                                        .getUsername());
                                reply.setReplyTo(comments.get(parentPositon).getReplies().get(childPostion)
                                        .getUsername());
                                comments.get(parentPositon).getReplies()
                                        .add(reply);
                                comments.get(parentPositon).update(ShowCookingDesActivity.this, comments.get(parentPositon).getObjectId(), new UpdateListener() {
                                    @Override
                                    public void onSuccess() {
                                        Log.i("bmob","更新成功：++");
                                        initComment();

                                    }

                                    @Override
                                    public void onFailure(int i, String s) {

                                    }
                                });



                            } else {
                                //回复楼主


                                replyLists.add(reply);
                                Log.i("我的回复", replyLists.size() + "");
                                comments.get(childPostion).setReplies(replyLists);
                                comments.get(childPostion).update(ShowCookingDesActivity.this, comments.get(childPostion).getObjectId(), new UpdateListener() {
                                    @Override
                                    public void onSuccess() {
                                        Log.i("bmob","更新成功：");
                                        initComment();
                                    }

                                    @Override
                                    public void onFailure(int i, String s) {

                                    }
                                });


                            }


                            customDialog.dismiss();
                            edt_reply.setText("");
                        }
                        break;
                }
            }
        });
        return customDialog;
    }

    Collection collection = new Collection();
    @Override
    public void onClick(View v) {

        switch (v.getId()){

            case R.id.show_des_collet:
                if (count == 0 ){

//                    User user = BmobUser.getCurrentUser(this,User.class);
                    Collection collection1 = new Collection();
                    collection1.setUser(user);
                    collection1.setAddCookStepEntity(addCookStepEntity);
                    collection1.save(this, new SaveListener() {
                        @Override
                        public void onSuccess() {
                            count=1;
                            initCollection();
                            show_des_collet.setImageResource(R.drawable.bottom_collect_yellow);
                            Toast.makeText(ShowCookingDesActivity.this,"收藏成功",Toast.LENGTH_LONG).show();

                        }

                        @Override
                        public void onFailure(int i, String s) {
                            Toast.makeText(ShowCookingDesActivity.this,"收藏失败",Toast.LENGTH_LONG).show();
                        }
                    });

                }else
                {

                    collection.delete(this, collection.getObjectId(), new DeleteListener() {
                        @Override
                        public void onSuccess() {
                            count=0;
                            show_des_collet.setImageResource(R.drawable.bottom_collention_grey_two);
                            Toast.makeText(ShowCookingDesActivity.this,"取消收藏",Toast.LENGTH_LONG).show();

                        }

                        @Override
                        public void onFailure(int i, String s) {
                            Toast.makeText(ShowCookingDesActivity.this,"取消收藏失败",Toast.LENGTH_LONG).show();
                        }
                    });
                }
                break;

            case R.id.show_des_comment:
                onCreateDialog(ONE_COMMENT_CODE, ONE_COMMENT_CODE);
                break;
            case R.id.show_des_back:
                finish();
        }

    }

    /**
     * 回复评论的监听（回复楼主）
     */
    private View.OnClickListener replyToCommentListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int position = (Integer) v.getTag();
            Log.i("我的评论",position +"");//外层listview 的 item 的值
            onCreateDialog(ONE_COMMENT_CODE, position);
        }
    };

    /**
     * 互相回复的监听（楼中楼）
     */
    private View.OnClickListener replyToReplyListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int parentPosition = (Integer) v.getTag(R.id.tag_first);
            Log.i("楼中楼",parentPosition+"");
            int childPosition = (Integer) v.getTag(R.id.tag_second);
            Log.i("楼中楼",childPosition+"");
            onCreateDialog(parentPosition, childPosition);

        }
    };

}




